package com.sywb.chuangyebao.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.MyArticleBean;
import com.sywb.chuangyebao.contract.PublishArticleContract;
import com.sywb.chuangyebao.view.dialog.AlertDialog;
import com.sywb.chuangyebao.view.dialog.SelectDialog;
import com.sywb.chuangyebao.widget.RichEditor;

import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.FileUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 发布文章
 *
 * @author duxl by 20180516
 */
public class PublishArticleActivity extends ActionbarActivity<PublishArticleContract.Presenter> implements PublishArticleContract.View, SelectDialog.OnItemClickListener {

    private TextView mTvTitle;
    private TextView mTvPublish;
    @BindView(R.id.ivSetFont_activity_publish_article)
    ImageView mIvSetFont;
    @BindView(R.id.etTitle_activity_publish_article)
    EditText mEtTitle;
    @BindView(R.id.richEditor_activity_publish_article)
    RichEditor mRichEditor;
    @BindView(R.id.rlSetting_activity_publish_article)
    RelativeLayout mRlSetting;
    @BindView(R.id.llFont_activity_publish_article)
    LinearLayout mLlFont;
    @BindView(R.id.ivBold_dialog_font)
    ImageView mIvBold;
    @BindView(R.id.ivItalic_dialog_font)
    ImageView mIvItalic;
    @BindView(R.id.ivUnderline_dialog_font)
    ImageView mIvUnderline;
    @BindView(R.id.ivH1_dialog_font)
    ImageView mIvH1;
    @BindView(R.id.ivH2_dialog_font)
    ImageView mIvH2;
    @BindView(R.id.ivH3_dialog_font)
    ImageView mIvH3;
    @BindView(R.id.ivH4_dialog_font)
    ImageView mIvH4;
    @BindView(R.id.tvProgress_activity_publish_article)
    TextView mTvProgress;

    private int mFontDefaultSize = 15;
    private int mFontH1Size = 25;
    private int mFontH2Size = 23;
    private int mFontH3Size = 20;
    private int mFontH4Size = 18;

    private MyArticleBean mArticleBean; // 如果是修改文章，那么此属性应该不为null

    private boolean isEdit = false;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_publish_article;
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);
        if (bundle == null) {
            bundle = getIntent().getExtras() == null ? new Bundle() : getIntent().getExtras();
        }
        mArticleBean = (MyArticleBean) bundle.getSerializable("p0");

        hasActionBar(true);
        mTvTitle = getView(R.id.actionbar_title);
        mTvTitle.setTextColor(Color.parseColor("#AAAAAA"));
        setTextCount(0);
        mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelOffset(R.dimen.sp_12));
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mTvTitle.getLayoutParams();
        lp.leftMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelOffset(R.dimen.dp_60), getResources().getDisplayMetrics());
        lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        lp.addRule(RelativeLayout.CENTER_VERTICAL);
        mTvTitle.setLayoutParams(lp);
        mTvPublish = addMenuTextItme(R.string.text_replease, R.color.colorGray, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFontDialog(false);
                mPresenter.publish(0);
            }
        });
        setPublishEnable(false);
        //mRichEditor.setEditorFontSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sp_15), getResources().getDisplayMetrics()));
        mRichEditor.setEditorFontSize(mFontDefaultSize);

        mRichEditor.setEditorFontColor(Color.parseColor("#AAAAAA"));
        mRichEditor.setPlaceholder(getString(R.string.content_hint));
        mRichEditor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onHtmlChange(String html, String text) {
                Logger.i("onHtmlChange=" + html);
                setTextCount(text.length());
                setPublishEnable();
            }
        });
        showFontDialog(false);
        mRichEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    showFontDialog(false);
                    mRlSetting.setVisibility(View.GONE);
                } else {
                    mRlSetting.setVisibility(View.VISIBLE);
                }
            }
        });
        mRichEditor.setOnSelectionChangeListner(new RichEditor.OnSelectionChangeListener() {
            @Override
            public void onSelectionChange() {
                if (mLlFont.isShown()) {
                    showFontDialog(true);
                }
            }
        });
        mRichEditor.setOnImageClickListener(new RichEditor.OnImageClickListener() {
            @Override
            public void onImageClick(String imgId) {
                SelectDialog dialog = SelectDialog.newInstance(null);
                dialog.setData(imgId);
                dialog.setItems(R.array.img_click_options);
                dialog.setOnItemClickListener(PublishArticleActivity.this);
                dialog.show(getMyFragmentManager(), "selectDialog");
            }
        });

        mEtTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                setPublishEnable();
            }
        });
        mTvProgress.setVisibility(View.GONE);
        mRlSetting.setVisibility(View.GONE);

        if (mArticleBean != null) { // 修改文章
            mEtTitle.setText(mArticleBean.title);
            mEtTitle.setSelection(mEtTitle.length());
            mRichEditor.setHtml(mArticleBean.content);

        }
    }

    @Override
    public void onItemClick(SelectDialog dialog, int position) {
        if (position == 0) { // 点击删除图片
            mRichEditor.removeImg(dialog.getData().toString());
        }
    }

    @Override
    public void exit() {
        final String title = mEtTitle.getText().toString().trim();
        final String html = mRichEditor.getHtml();

        if (!TextUtils.isEmpty(title) || !TextUtils.isEmpty(html)) {
            String msg = getString(R.string.discard_msg);
            String leftBtn = getString(R.string.discard);
            String rightBtn = getString(R.string.save);
            AlertDialog dialog = AlertDialog.newInstance(null, msg, leftBtn, rightBtn, false);
            dialog.setCancelable(true);
            dialog.setClickListener(new AlertDialog.OnClickListener() {
                @Override
                public void onClick(int position) {
                    if (position == 0) {
                        PublishArticleActivity.super.exit();
                    } else {
                        mPresenter.publish(9);
                    }
                }
            });
            dialog.show(getMyFragmentManager(), "discardDialog");

        } else {
            super.exit();
        }
    }

    @OnClick(R.id.ivAddPic_activity_publish_article)
    public void onClickAddPic() {
        showFontDialog(false);
        // 进入相册,用不到的api可以不写
        PictureSelector.create(mActivity)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.style_picture_white)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(9)// 最大图片选择数量 int
                .minSelectNum(0)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(false)// 是否可预览视频 true or false
                .enablePreviewAudio(false) // 是否可播放音频 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))// 自定义拍照保存路径,可不填
                .enableCrop(true)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                // .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                //.withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                // .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
                // .isGif()// 是否显示gif图片 true or false
                .compressSavePath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))//压缩图片保存地址
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(false)// 是否开启点击声音 true or false
                // .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
                // .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                // .cropCompressQuality()// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                // .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                // .videoQuality()// 视频录制质量 0 or 1 int
                //  .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                // .recordVideoSecond()//视频秒数录制 默认60s int
                .forResult(10001);//结果回调onActivityResult code
    }

    @OnClick(R.id.ivSetFont_activity_publish_article)
    public void onClickSetFont() {
        showFontDialog(!mLlFont.isShown());
        mRichEditor.requestFocus();
        //mRichEditor.focusEditor();
    }

    @OnClick(R.id.ivBold_dialog_font)
    public void onFontBoldClick(View v) {
        v.setSelected(!v.isSelected());
        mRichEditor.setBold();
        showFontDialog(false);
    }

    @OnClick(R.id.ivItalic_dialog_font)
    public void onFontItalicClick(View v) {
        v.setSelected(!v.isSelected());
        mRichEditor.setItalic();
        showFontDialog(false);
    }

    @OnClick(R.id.ivUnderline_dialog_font)
    public void onFontUnderlineClick(View v) {
        v.setSelected(!v.isSelected());
        mRichEditor.setUnderline();
        showFontDialog(false);
    }

    @OnClick(R.id.ivMark_dialog_font)
    public void onFontMarkClick(View v) {
        mRichEditor.mark();
        showFontDialog(false);
    }

    @OnClick(R.id.ivH1_dialog_font)
    public void onFontH1Click(View v) {
        if (v.isSelected()) {
            v.setSelected(false);
            mRichEditor.setFontSize2(mFontDefaultSize);
        } else {
            switchViewSelectState(mIvH1, mIvH2, mIvH3, mIvH4);
            mRichEditor.setFontSize2(mFontH1Size);
        }
        showFontDialog(false);
    }

    @OnClick(R.id.ivH2_dialog_font)
    public void onFontH2Click(View v) {
        if (v.isSelected()) {
            v.setSelected(false);
            mRichEditor.setFontSize2(mFontDefaultSize);
        } else {
            switchViewSelectState(mIvH2, mIvH1, mIvH3, mIvH4);
            mRichEditor.setFontSize2(mFontH2Size);
        }
        showFontDialog(false);
    }

    @OnClick(R.id.ivH3_dialog_font)
    public void onFontH3Click(View v) {
        if (v.isSelected()) {
            v.setSelected(false);
            mRichEditor.setFontSize2(mFontDefaultSize);
        } else {
            switchViewSelectState(mIvH3, mIvH2, mIvH1, mIvH4);
            mRichEditor.setFontSize2(mFontH3Size);
        }
        showFontDialog(false);
    }

    @OnClick(R.id.ivH4_dialog_font)
    public void onFontH4Click(View v) {
        if (v.isSelected()) {
            v.setSelected(false);
            mRichEditor.setFontSize2(mFontDefaultSize);
        } else {
            switchViewSelectState(mIvH4, mIvH2, mIvH3, mIvH1);
            mRichEditor.setFontSize2(mFontH4Size);
        }
        showFontDialog(false);
    }

    /**
     * 传入的第一个v设置为true，其它设置为false
     *
     * @param v
     */
    private void switchViewSelectState(View v0, View... v) {
        if (v0 != null) {
            v0.setSelected(true);
        }

        for (int i = 0; i < v.length; i++) {
            v[i].setSelected(false);
        }
    }

    /**
     * 设置标题栏显示文字个数
     *
     * @param count 文字的个数
     */
    @SuppressLint("StringFormatMatches")
    private void setTextCount(int count) {
        mTvTitle.setText(getString(R.string.text_count, count));
    }

    /**
     * 设置发布按钮是否可用(注：标题、内容有数据时，“发布”由灰色显示为红色)
     *
     * @param enable
     */
    private void setPublishEnable(boolean enable) {
        mTvPublish.setEnabled(enable);
        int colorResId = enable ? R.color.colorTheme : R.color.colorGray;
        mTvPublish.setTextColor(ContextCompat.getColor(this, colorResId));
    }

    private void setPublishEnable() {
        String title = mEtTitle.getText().toString().trim();
        // 标题不为空并且正文有内容（正文有文字或者有图片都表示不为空）
        setPublishEnable(isEdit && !TextUtils.isEmpty(title) && (!TextUtils.isEmpty(mRichEditor.getText()) || mRichEditor.getHtml().indexOf("img") != -1));
        isEdit = true;
    }

    private void showFontDialog(boolean show) {
        if (!show) {
            mLlFont.setVisibility(View.GONE);
        } else {
            mRichEditor.getBIUHState(new RichEditor.OnJsCallBackListener() {
                @Override
                public void onJsCallBack(String value) {
                    int biuh = Integer.parseInt(value);
                    boolean b = (biuh & (1 << 0)) == (1 << 0); // 粗体
                    boolean i = (biuh & (1 << 1)) == (1 << 1); // 斜体
                    boolean u = (biuh & (1 << 2)) == (1 << 2); // 下划线

                    mIvBold.setSelected(b);
                    mIvItalic.setSelected(i);
                    mIvUnderline.setSelected(u);

                    boolean h1 = (biuh & (1 << 3)) == (1 << 3); // h1
                    boolean h2 = (biuh & (1 << 4)) == (1 << 4); // h2
                    boolean h3 = (biuh & (1 << 5)) == (1 << 5); // h3
                    boolean h4 = (biuh & (1 << 6)) == (1 << 6); // h4
                    if (h1) {
                        switchViewSelectState(mIvH1, mIvH2, mIvH3, mIvH4);
                    } else if (h2) {
                        switchViewSelectState(mIvH2, mIvH1, mIvH3, mIvH4);
                    } else if (h3) {
                        switchViewSelectState(mIvH3, mIvH2, mIvH1, mIvH4);
                    } else if (h4) {
                        switchViewSelectState(mIvH4, mIvH2, mIvH3, mIvH1);
                    } else {
                        switchViewSelectState(null, mIvH1, mIvH2, mIvH3, mIvH4);
                    }

                    mLlFont.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    @Override
    public TextView getProgress() {
        return mTvProgress;
    }

    @Override
    public EditText getEtTitle() {
        return mEtTitle;
    }

    @Override
    public RichEditor getRichEditor() {
        return mRichEditor;
    }

    @Override
    public int getArticleId() {
        return mArticleBean != null ? mArticleBean.id : -1;
    }

    @Override
    public void showPublishResultDialog(int type) {
        String msg = type == 3 ? getString(R.string.publish_success) : getString(R.string.draft_success);
        String btn = getString(R.string.btn_confirm);
        AlertDialog dialog = AlertDialog.newInstance(null, msg, btn, null, true);
        dialog.setClickListener(new AlertDialog.OnClickListener() {
            @Override
            public void onClick(int position) {
                PublishArticleActivity.super.exit();
            }
        });
        dialog.show(getMyFragmentManager(), "showPublishResultDialog");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mLlFont.isShown()) {
                showFontDialog(false);
            } else {
                exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            if (selectList == null || selectList.size() == 0) {
                return;
            }

            for (LocalMedia localMedia : selectList) {
                String path = localMedia.getCompressPath();
                localMedia.position = java.util.UUID.randomUUID().hashCode();
                mRichEditor.insertImage(String.valueOf(localMedia.position), path);
            }

            mPresenter.uploadPicture(selectList);
        }
    }
}
